/*
 * Copyright (c) 2011 University of Tartu
 */
package org.qsardb.visitor;

import java.io.*;
import java.util.*;
import java.util.logging.*;

import org.qsardb.application.*;
import org.qsardb.model.*;

import com.beust.jcommander.*;
import com.beust.jcommander.Parameter;

public class VisitorRunner {

	@Parameter (
		names = {"--log-level"},
		description = "The logging level. " + LevelConverter.MESSAGE,
		converter = LevelConverter.class
	)
	private Level level = Level.INFO;

	@Parameter (
		names = "--recursive",
		description = "Recurse into directories",
		arity = 1
	)
	private boolean recursive = true;

	@Parameter (
		required = true
	)
	private List<String> paths = null;


	private VisitorRunner(){
	}

	static
	public void main(String... args) throws Exception {
		JCommander commander = new JCommander();
		commander.setProgramName(VisitorRunner.class.getName() + " <visitor class>");

		VisitorRunner visitorRunner = new VisitorRunner();

		commander.addObject(visitorRunner);

		Visitor visitor;

		try {
			Class<?> clazz = Class.forName(args[0]);

			visitor = (Visitor)clazz.newInstance();
		} catch(Exception e){
			commander.usage();

			System.exit(-1);

			return;
		}

		commander.addObject(visitor);

		try {
			String[] visitorArgs = Arrays.copyOfRange(args, 1, args.length);

			commander.parse(visitorArgs);
		} catch(ParameterException pe){
			commander.usage();

			System.exit(-1);

			return;
		}

		visitorRunner.run(visitor);
	}

	private void run(Visitor visitor) throws Exception {
		logger.setLevel(this.level);

		visitor.begin();

		try {
			List<String> paths = this.paths;
			for(String path : paths){
				File file = new File(path);

				run(visitor, file);
			}
		} finally {
			visitor.end();
		}
	}

	private void run(Visitor visitor, File file) throws Exception {

		if(file.isFile()){
			runFile(visitor, file);
		} else

		if(file.isDirectory()){
			runDirectory(visitor, file);
		}
	}

	private void runFile(Visitor visitor, File file) throws Exception {
	}

	private void runDirectory(Visitor visitor, File dir) throws Exception {
		File archive = new File(dir, "archive.xml");

		if(archive.isFile()){
			Storage storage = StorageUtil.openInput(dir);

			try {
				visitor.accept(storage);
			} finally {
				storage.close();
			}
		} else

		{
			if(!this.recursive){
				return;
			}

			File[] files = dir.listFiles();
			for(File file : files){
				run(visitor, file);
			}
		}
	}

	private static final Logger logger = Logger.getLogger(VisitorRunner.class.getName());
}